import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';

import { Card, Button, message, Popconfirm, Tabs } from 'antd';

import RenderAuthorized from '@/components/Authorized';
import styles from './styles.less';

import BillEditor from '../Components/BillEditor';

const TabPane = Tabs.TabPane;


const ModelName = "hbl";
@connect(({ user, loading, mbl }) => ({
  loading: loading.models[ModelName],
  mbl: mbl.current,
  cUser: user.currentUser,
}))
class Comp extends PureComponent {
  state = {
    list: [],
    mbl: {},

    activeKey: '0',
  };

  componentDidMount() {
    const { mbl } = this.props;
    if (mbl)
      this.setState({ mbl: mbl }, () => {
        this.loadData();
      });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.mbl)
      if (nextProps.mbl !== this.props.mbl) {
        this.setState({ mbl: nextProps.mbl }, () => {
          this.loadData();
        });
      }
  }

  loadData() {
    const { dispatch } = this.props;
    const { mbl } = this.state;
    dispatch({
      type: `${ModelName}/getByMBLNo`,  //查询一个主单的所有分单列表
      payload: mbl ? mbl.objectNumber : '',
      callback: resp => {
        this.setState({
          list: resp
        }, () => {
          if (resp.length > 0) {
            this.setActiveKey();
          }
        });
      }
    });
  }

  setActiveKey() {
    const { list } = this.state;
    let maxId = Math.max.apply(Math, list.map(o => o.id));
    this.setState({ activeKey: String(maxId) })
  }

  handleAddClick() {
    const { dispatch, mbl } = this.props;

    const vm = {
      id: 0,
      mblId: mbl.id
    }
    dispatch({
      type: 'hbl/addNew',
      payload: vm,
      callback: resp => {
        if (resp) // 如果有错，则不重新加载，例如： 如果主单有货柜，则不能再添加分单.
          this.loadData();
      }
    });
  }

  handleDelete = (item) => {
    const { dispatch } = this.props;
    const { list } = this.state;
    dispatch({
      type: 'hbl/remove',
      payload: item.id,
      callback: resp => {
        if (resp)
          this.setState({ list: list.filter(r => r.id !== item.id) }, () => {
            this.setActiveKey();
          });
      }
    })
  }

  handleSave = (item) => {
    const { dispatch } = this.props;
    const { mbl } = this.props;
    const vm = {
      ...item,
      objectNumber: item.objectNumber.trim() == mbl.objectNumber.trim() ? '' : item.objectNumber, // 如果是与主单的单号一样，则换成空的.
    }

    console.log("UPDATE HBL:", vm);

    dispatch({
      type: 'hbl/update',
      payload: vm,
      callback: resp => {
        if (resp) {
          dispatch({
            type: 'relationer/get',
          })
          this.loadData();
          message.success('保存成功!');
        }
      }
    })
  }

  handlePrint = (item) => {
    var key = item.objectNumber || item.id;
    window.open(`/api/report/PrintHBL?key=${key}`, 'blank');
  }

  handleDownload = (item, isTelex) => {
    var key = item.objectNumber || item.id;
    window.open(`/api/report/DownloadHBL?key=${key}&isTelex=${isTelex}`, 'blank');
  }

  onChange = (activeKey) => {
    this.setState({ activeKey });
  }

  render() {
    const { cUser } = this.props;
    const { list, mbl, activeKey } = this.state;

    const Authorized = RenderAuthorized(cUser.sys_Role.enCode);

    const actions = (item) => (
      <div>
        <a onClick={() => this.handlePrint(item)} >打印</a>
        <a style={{ marginLeft: '8px' }} onClick={() => this.handleDownload(item, false)}>下载</a>
        <a style={{ marginLeft: '8px' }} onClick={() => this.handleDownload(item, true)}>电放</a>

        <Authorized authority={['SysAdmin', 'SysOperator']}>
          <Popconfirm title="确定要删除吗?" onConfirm={() => this.handleDelete(item)}>
            <a style={{ marginLeft: '8px', display: mbl.isLock === 1 ? 'none' : '' }}>删除</a>
          </Popconfirm>
        </Authorized>

      </div>
    );

    return (
      <Card
        className={styles.card}
      >
        <Tabs
          onChange={this.onChange}
          activeKey={activeKey}
          tabBarExtraContent={
            <Authorized authority={['SysAdmin', 'SysOperator']} >
              <Button type="primary" disabled={mbl && mbl.isLock === 1} onClick={(e) => this.handleAddClick(e)} >添加</Button>
            </Authorized>
          }
          onEdit={this.onEdit}
        >
          {list.map(item => (
            <TabPane tab={item.objectNumber || mbl.objectNumber} key={item.id} closable={false}>
              <BillEditor key={item.id} bill={item} actions={actions(item)} onDelete={this.handleDelete} onSave={this.handleSave} />
            </TabPane>)
          )}
        </Tabs>

      </Card >
    );
  }
}

export default Comp;
